package com.example.seakdreamandroid.playHistory;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.MusicStoryPlayerActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.playHistory.HistoryRecord;
import com.example.seakdreamandroid.whiteNoise.WhiteNoiseActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PlayHistoryActivity extends Activity {
    private static final int REFRESH = 3;
    private static final int LOAD_MORE = 4;
    private ValueAnimator animator;
    private SmartRefreshLayout sm;
    private RecyclerView rv;
    private ImageView imgReturn;
    private ImageView imgPlay;
    private ProgressBar playProgressBar;
    private ImageView imgClean;
    private PlayHistoryAdapter adapter;
    private User user;
    private static final int OK = 5;
    private static final int FAILURE = 6;
    private static final String TAG = "PlayHistoryActivity";
    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what){
                case OK:
                    if(msg.arg1 == REFRESH){
                        sm.finishRefresh();
                        adapter.notifyDataSetChanged();
                    }else{
                        sm.finishLoadMore();
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case FAILURE:
                    Toast.makeText(PlayHistoryActivity.this,"请求数据失败，请检查网络",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };
    private int mPage = 1;
    private List<HistoryRecord> mHistories;

    public ValueAnimator getAnimator() {
        return animator;
    }

    public ImageView getImgPlay() {
        return imgPlay;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_history);
        user = (User) getApplicationContext();
        mHistories = new ArrayList<HistoryRecord>();
        getView();
        initAnimator();
        initSmartRefreshLayout();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(manager);
        getHistoryDataUsePage(REFRESH);
        adapter = new PlayHistoryAdapter(mHistories,this,user.getUserId());
        rv.setAdapter(adapter);
        setListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initAnimator() {
        animator = ValueAnimator.ofInt(0,360);
        animator.setDuration(3000);
        animator.setRepeatCount(-1);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int angle = (int) animation.getAnimatedValue();
                imgPlay.setRotation(angle);
            }
        });
    }

    private void setListener() {
        imgReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlayHistoryActivity.this.finish();
            }
        });
        imgClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userId = user.getUserId();
                Log.i(TAG,userId);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(Constant.BASE_URL + "History/deleteAllHistory?userId=" + userId)
                        .get()
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.i(TAG,"onFailure，清空播放历史失败");
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PlayHistoryActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        Log.i(TAG,"onResponse，resultStr=" + response.body().string());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sm.autoRefresh(0);
                            }
                        });
                    }
                });
            }

        });
        imgPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到音乐播放界面
                /**
                 * 杨锐涵添加
                 */
                if(!user.isMSPIsPlay() && !user.isWhiteNoiseIsPlay()){
                    Intent intent = new Intent(PlayHistoryActivity.this, WhiteNoiseActivity.class);
                    startActivity(intent);
                }
                if (user.isMSPIsPlay()){
                    Intent intent = new Intent();
                    intent.setClass(PlayHistoryActivity.this, MusicStoryPlayerActivity.class);
                    startActivity(intent);
                }
                if (user.isWhiteNoiseIsPlay()) {
                    Intent intent = null;
                    Bundle bundle = new Bundle();
                    user = (User) getApplication();
                    intent = new Intent(PlayHistoryActivity.this, WhiteNoisePlayerActivity.class);
                    startActivityForResult(intent, 1);
                }

            }
        });
        sm.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPage = 1;
                getHistoryDataUsePage(REFRESH);
            }
        });
        sm.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                getHistoryDataUsePage(LOAD_MORE);
            }
        });


    }

    private void getHistoryDataUsePage(int type) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"History/getHistoryRecordUsePage?userId=" + user.getUserId() + "&page=" + mPage)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i(TAG,"获取网络数据失败，onFailure");
                Message msg = handler.obtainMessage();
                msg.what = FAILURE;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resultStr = response.body().string();
                try{
                    JSONObject obj = new JSONObject(resultStr);
                    if(obj.getString("data").equals("null")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PlayHistoryActivity.this, "没有更多了，去上面看看吧", Toast.LENGTH_LONG).show();
                            }
                        });
                        sm.setEnableLoadMore(false);
                        return;
                    }
                    JSONArray recordResult = obj.getJSONArray("data");
                    if(recordResult.length()<20){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PlayHistoryActivity.this,"没有更多了，去上面看看吧",Toast.LENGTH_LONG).show();
                            }
                        });
                        sm.setEnableLoadMore(false);
                    }else{
                        sm.setEnableLoadMore(true);
                    }
                    if(type==REFRESH){
                        mHistories.clear();
                    }
                    for(int i = 0; i < recordResult.length(); i++){
                        JSONObject temp = recordResult.getJSONObject(i);
                        HistoryRecord record = new HistoryRecord();
                        record.setHistoryId(temp.getInt("historyId"));;
                        record.setWhiteNoise(temp.getBoolean("whiteNoise"));
                        if(record.isWhiteNoise()){
                            Log.i(TAG,temp.toString());
                            record.setWhiteNoiseCount(temp.getInt("whiteNoiseCount"));
                            if(record.getWhiteNoiseCount() >= 1){
                                record.setWhiteId1(temp.getString("whiteId1"));
                                record.setWhiteNoiseImg1(temp.getString("whiteNoiseImg1"));
                                record.setWhiteNoiseName1(temp.getString("whiteNoiseName1"));
                                record.setWhiteNoiseUrl1(temp.getString("whiteNoiseUrl1"));
                            }
                            if(record.getWhiteNoiseCount() >= 2){
                                record.setWhiteId2(temp.getString("whiteId2"));
                                record.setWhiteNoiseImg2(temp.getString("whiteNoiseImg2"));
                                record.setWhiteNoiseName2(temp.getString("whiteNoiseName2"));
                                record.setWhiteNoiseUrl2(temp.getString("whiteNoiseUrl2"));
                            }
                            if(record.getWhiteNoiseCount() >= 3){
                                record.setWhiteId3(temp.getString("whiteId3"));
                                record.setWhiteNoiseImg3(temp.getString("whiteNoiseImg3"));
                                record.setWhiteNoiseName3(temp.getString("whiteNoiseName3"));
                                record.setWhiteNoiseUrl3(temp.getString("whiteNoiseUrl3"));
                            }
                        }else{
                            record.setAudioId(temp.getString("audioId"));
                            record.setAudioImg(temp.getString("audioImg"));
                            record.setAudioName(temp.getString("audioName"));
                            record.setAudioUrl(temp.getString("audioUrl"));
                            record.setAudioType(temp.getString("audioType"));
                            record.setAudioAuthor(temp.getString("audioAuthor"));
                        }
                        mHistories.add(record);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }finally{
                    if((WhiteNoisePlayerService.getPlayState() != WhiteNoisePlayerService.NONE && WhiteNoisePlayerService.getPlayState() != WhiteNoisePlayerService.ERROR) || user.isMSPIsPlay()){
                        adapter.setCurrentPlay(0);
                    }
                    Message msg = handler.obtainMessage();
                    msg.what = OK;
                    msg.arg1 = type;
                    handler.sendMessage(msg);
                }
            }
        });
    }


    private void cleanHistory() {

    }


    private void initSmartRefreshLayout() {
        sm.setRefreshHeader(new ClassicsHeader(this));
        sm.setRefreshFooter(new ClassicsFooter(this));
    }

    private void getView() {
        imgReturn = findViewById(R.id.img_return);
        imgClean = findViewById(R.id.clean);
        playProgressBar = findViewById(R.id.progress_bar);
        imgPlay = findViewById(R.id.play);
        sm = findViewById(R.id.sm);
        rv = findViewById(R.id.rv);
    }

    public void playMusic(int adapterPosition) {

        animator.start();
    }
    public void pauseMusic(){
        animator.pause();
    }
}